package challenge.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;

import challenge.model.Dataset;
import challenge.model.Question;

public class DatasetService {

	final Logger log = LoggerFactory.getLogger(DatasetService.class);
	
	private Resource input;

	private String output;

	private Jaxb2Marshaller jaxb2Marshaller;

	private Dataset dataset = null;


	

	public Dataset getDataset() {
		log.debug("get dataset");
		try {
			if (dataset == null) {
				log.debug("init from xml file");
				log.debug("input resource URL: "+ input.getURL());
				Source source = new StreamSource(input.getInputStream());
				dataset = (Dataset) jaxb2Marshaller.unmarshal(source);
				log.debug("found dataset: "+ dataset.getId());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dataset;
	}



	public void setDataset(Dataset dataset) {
		this.dataset = dataset;
	}



	public Resource getInput() {
		return input;
	}

	public void setInput(Resource input) {
		this.input = input;
	}

	public String getOutput() {
		return output;
	}

	public void setOutput(String output) {
		this.output = output;
	}

	public Jaxb2Marshaller getJaxb2Marshaller() {
		return jaxb2Marshaller;
	}

	public void setJaxb2Marshaller(Jaxb2Marshaller jaxb2Marshaller) {
		this.jaxb2Marshaller = jaxb2Marshaller;
	}
	
	
	
	private Question findQuestionByString(String string){
    	for (Question question : getDataset().getQuestion()) {
            if (question.getString().contains(string)) {
                return question;
            }
        }
        return null; 
    } 
	
	
	public void addResult(String string, String sparql){
		Question question = findQuestionByString(string);
		question.setQuery(sparql);
		// delete answers
		question.getAnswers().getAnswer().clear();
	}
	
	public String getResult(String string){
		Question question = findQuestionByString(string);
		return question.getQuery();
	}
	
	public void saveDataset(){
		FileOutputStream fos = null;
		File fileOut = new File(output);
		try {
			fos = new FileOutputStream(fileOut);
			Result result = new StreamResult(fos);
			jaxb2Marshaller.marshal(getDataset(), result);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{			
			if(fos!=null){
				try {
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	


}
